package com.chanricle.mixtoolset.connection;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

import com.chanricle.mixtoolset.exception.HttpURLFormatException;

/**
 * MixToolsetConnector Implementation
 * 
 * @author Chanricle King
 * 
 */
public class MixToolsetConnectorImpl implements MixToolsetConnector {
	private static MixToolsetConnector connector = new MixToolsetConnectorImpl();

	private MixToolsetConnectorImpl() {

	}

	public static MixToolsetConnector getInstance() {
		return connector;
	}

	@Override
	public String GET(String httpUrl) {
		if (httpUrl.startsWith("http://") || httpUrl.startsWith("https://")) {

			BufferedReader reader = null;
			StringBuilder sb = new StringBuilder();

			try {
				URL url = new URL(httpUrl);

				URLConnection urlConn = url.openConnection();
				reader = new BufferedReader(new InputStreamReader(
						urlConn.getInputStream(), "UTF-8"));

				String s;

				while ((s = reader.readLine()) != null) {
					sb.append(s);
				}
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return sb.toString();
		} else {
			throw new HttpURLFormatException(
					"HTTP url required start with 'http://' or 'https://'");
		}

	}

	@Override
	public String GET(String httpUrl, Map<String, String> params) {
		StringBuffer parameterComponent = new StringBuffer("?");
		boolean firstParam = true;
		for (String key : params.keySet()) {
			if (!firstParam) {
				parameterComponent.append("&");
			}
			if (firstParam && "?".equals(parameterComponent.toString())) {
				firstParam = false;
			}

			parameterComponent.append(key).append("=").append(params.get(key));
		}

		return GET(httpUrl + parameterComponent.toString());
	}

	@Override
	public String POST(String httpUrl) {
		return POST(httpUrl, null);
	}

	@Override
	public String POST(String httpUrl, Map<String, String> params) {
		if (httpUrl.startsWith("http://") || httpUrl.startsWith("https://")) {

			StringBuffer sb = new StringBuffer();
			DataOutputStream out;
			BufferedReader reader;
			HttpURLConnection connection;

			try {
				URL postUrl = new URL(httpUrl);

				connection = (HttpURLConnection) postUrl.openConnection();

				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				connection.setUseCaches(false);
				connection.setInstanceFollowRedirects(true);
				connection.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");

				connection.connect();

				out = new DataOutputStream(connection.getOutputStream());

				/* Deal parameter */
				if (params != null) {
					StringBuffer parameterComponent = new StringBuffer();
					boolean firstParam = true;
					for (String key : params.keySet()) {
						if (!firstParam) {
							parameterComponent.append("&");
						}
						if (firstParam && parameterComponent.length() == 0) {
							firstParam = false;
						}

						parameterComponent
								.append(key)
								.append("=")
								.append(URLEncoder.encode(params.get(key),
										"utf-8"));
					}
					out.writeBytes(parameterComponent.toString());
					out.flush();
					out.close();
				}

				reader = new BufferedReader(new InputStreamReader(
						connection.getInputStream(), "UTF-8"));
				String line;

				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				reader.close();
				connection.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return sb.toString();
		} else {
			throw new HttpURLFormatException(
					"HTTP url required start with 'http://' or 'https://'");
		}
	}
	
}
